from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.utils.decorators import login_required
from comment.modules.user import User
from comment.modules.product_rate import Product_rate
from comment.modules.deal_record import DealRecord
from comment.modules import db
from financial.resources.transaction.serializer import DealRecordPaginateSerializer


class Deal_Resource(Resource):
    """交易记录的资源类"""

    def get(self):
        """交易记录的列表"""
        rp = RequestParser()
        rp.add_argument('start') # 起始时间
        rp.add_argument('end') # 结束时间
        rp.add_argument('deal_type') # 交易类型 初始值是0，0：全部
        rp.add_argument('curPage', required=True) # 当前页号
        rp.add_argument('per_page', required=True) # 每页显示的条数

        args = rp.parse_args()
        start = args.get('start')
        end = args.get('end')
        deal_type = 0 if args.get('deal_type') == None else int(args.get('deal_type'))
        cur_page = int(args.get('curPage'))
        page_size = int(args.get('per_page'))

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()
        # 得到一个查询对象
        q = DealRecord.query
        # 第一个过滤：根据交易的类型来过滤
        if deal_type > 0:
            q = q.filter(DealRecord.aType == deal_type)
        # 第二个过滤： 根据用户ID (当前用户如果是管理员，可以查询所有的，否则只能查询自己的)
        if user.role == 0:
            q = q.filter(DealRecord.aUserId == user_id)

        # 第三个过滤
        if start and end:
           q = q.filter(db.cast(DealRecord.aDate, db.DATE) >= db.cast(start, db.DATE))\
               .filter(db.cast(DealRecord.aDate, db.DATE) <= db.cast(end, db.DATE))

        data = q.paginate(cur_page, page_size, error_out=False)

        data = DealRecordPaginateSerializer(data).to_dict()

        return {'msg': 'success', 'data': data}